package com.yuanxin.networking;

import android.util.Log;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;

/**
 * Created by lemon on 2016/12/19.
 */

public class Uploader {
    private static final String TAG = "Uploader";

    public void UploadMultiFile(final String actionURL,
                                final List<FileInfoBean> fileList, final Map<String, String> params, final int type, final NetWorkCallBack netWorkCallBack) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//
//                    ResponseInfoBean responseInfoBean = post(actionURL, params, fileList, type);
//                    netWorkCallBack.success(responseInfoBean);
//                } catch (Exception ex) {
//                    netWorkCallBack.error(ex);
//                }
//            }
//        }).start();

        PostRequest<String> postRequest = OkGo.<String>post(actionURL).params(params);
        for (int i = 0; i < fileList.size(); i++) {
            FileInfoBean fileInfoBean = fileList.get(i);

            String suffixName = fileInfoBean.getFormatPath().substring(fileInfoBean.getFormatPath().lastIndexOf('.'));//取出文件的后缀名  .png   .jpg
            if (type == 0) {
                suffixName = fileInfoBean.getFormatPath().substring(fileInfoBean.getFormatPath().lastIndexOf('.'));//取出文件的后缀名  .png   .jpg
            } else if (type == 1) {
                suffixName = fileInfoBean.getAudioPath().substring(fileInfoBean.getAudioPath().lastIndexOf('.'));//取出文件的后缀名  .amr
            } else if (type == 2) {
                suffixName = fileInfoBean.getVideoPath().substring(fileInfoBean.getVideoPath().lastIndexOf('.'));//取出文件的后缀名  .amr
            }
            String fileName = fileInfoBean.getObjectKey() + suffixName;//objectKey  就是服务器上的文件名     .jpg

            postRequest.params(fileInfoBean.getObjectKey(),
                    LocalUtil.byte2File(fileInfoBean.getFileByte(), fileInfoBean.getFormatPath(), fileName),
                    fileName, MediaType.parse(LocalUtil.guessMimeType(fileName)));
        }

        postRequest.execute(new Callback<String>() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {

            }

            @Override
            public void onSuccess(Response<String> response) {
                ResponseInfoBean responseInfoBean = new ResponseInfoBean();
                StringBuffer b = new StringBuffer();
                int ch;
                try {
                    InputStreamReader inread = new InputStreamReader(response.getRawResponse().body().byteStream(), "utf-8");
                    while ((ch = inread.read()) != -1) {
                        b.append((char) ch);
                    }
                    responseInfoBean.setMessage(b.toString());
                    responseInfoBean.setCode(response.getRawResponse().code());
                   // Log.d(TAG, "upload onSuccess : " + b.toString());
                    netWorkCallBack.success(responseInfoBean);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    netWorkCallBack.error(e);
                } catch (IOException e) {
                    e.printStackTrace();
                    netWorkCallBack.error(e);
                }
            }

            @Override
            public void onError(Response<String> response) {
                netWorkCallBack.error(new Exception(response.getException()));
            }

            @Override
            public void onCacheSuccess(Response<String> response) {

            }


            @Override
            public void onFinish() {

            }

            @Override
            public void uploadProgress(Progress progress) {

            }

            @Override
            public void downloadProgress(Progress progress) {

            }

            @Override
            public String convertResponse(okhttp3.Response response) throws Throwable {
                return null;
            }
        });

    }

    public void downFile(final String url, final DownFileCallBack downFileCallBack) {

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    InputStream inputStream = downFile(url);
//                    downFileCallBack.success(inputStream);
//                } catch (Exception ex) {
//                    downFileCallBack.error(ex);
//                }
//            }
//        }).start();
        OkGo.<InputStream>get(url).execute(new Callback<InputStream>() {
            @Override
            public void onStart(Request<InputStream, ? extends Request> request) {

            }

            @Override
            public void onSuccess(final Response<InputStream> response) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            downFileCallBack.success(response.body());
                        } catch (Exception ex) {
                            downFileCallBack.error(ex);
                        }
                    }
                }).start();
            }

            @Override
            public void onCacheSuccess(Response<InputStream> response) {

            }

            @Override
            public void onError(Response<InputStream> response) {
                downFileCallBack.error(new Exception(response.getException()));
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void uploadProgress(Progress progress) {

            }

            @Override
            public void downloadProgress(Progress progress) {

            }

            @Override
            public InputStream convertResponse(okhttp3.Response response) throws Throwable {
                return response.body().byteStream();
            }
        });
    }


//    private InputStream downFile(String urlStr)
//            throws IOException {
//        URL url = new URL(urlStr);
//        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//        InputStream inputStream = httpConn.getInputStream();
//        return inputStream;
//    }
//
//    private ResponseInfoBean post(String actionUrl, Map<String, String> params,
//                                  List<FileInfoBean> files, int type) throws IOException {
//
//        String BOUNDARY = java.util.UUID.randomUUID().toString();
//        String PREFIX = "--", LINEND = "\r\n";
//        String MULTIPART_FROM_DATA = "multipart/form-data";
//        String CHARSET = "UTF-8";
//        URL uri = new URL(actionUrl);
//        //上传---需要一个地址
//        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
//        conn.setReadTimeout(5 * 60 * 1000);
//        conn.setConnectTimeout(5 * 60 * 1000);
//        conn.setDoInput(true);
//        conn.setDoOutput(true);
//        conn.setUseCaches(false);
//        conn.setRequestMethod("POST");
//        conn.setRequestProperty("connection", "keep-alive");
//        conn.setRequestProperty("Charsert", "UTF-8");
//        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
//                + ";boundary=" + BOUNDARY);
//
//
//        StringBuilder sb = new StringBuilder();
//        for (Map.Entry<String, String> entry : params.entrySet()) {
//            sb.append(PREFIX);
//            sb.append(BOUNDARY);
//            sb.append(LINEND);
//            sb.append("Content-Disposition: form-data; name=\""
//                    + entry.getKey() + "\"" + LINEND);
//            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
//            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
//            sb.append(LINEND);
//            sb.append(entry.getValue());
//            sb.append(LINEND);
//        }
//
//        DataOutputStream outStream = new DataOutputStream(conn
//                .getOutputStream());
//        outStream.write(sb.toString().getBytes());
//
//
//        if (files != null)
//            for (int i = 0; i < files.size(); i++) {
//                FileInfoBean fileInfoBean = files.get(i);
//                String suffixName="";
//                if (type == 0) {
//                    suffixName = fileInfoBean.getFormatPath().substring(fileInfoBean.getFormatPath().lastIndexOf('.'));//取出文件的后缀名  .png   .jpg
//                }
//                else if(type==1){
//                    suffixName = fileInfoBean.getAudioPath().substring(fileInfoBean.getAudioPath().lastIndexOf('.'));//取出文件的后缀名  .amr
//                }
//                else if(type==2) {
//                    suffixName = fileInfoBean.getVideoPath().substring(fileInfoBean.getVideoPath().lastIndexOf('.'));//取出文件的后缀名  .amr
//                }
//                String fileName = fileInfoBean.getObjectKey() + suffixName;//objectKey  就是服务器上的文件名     .jpg
//
//               // Log.e("uploadImage.....", "suffixName=" + suffixName + "   fileName=" + fileName);
//
//                //suffixName=.cateringapp/app_cache/5F17D623E15E5D71DFD762E1556AC535   fileName=985a8ebbc08c4443af5cdde57b0194ac.cateringapp/app_cache/5F17D623E15E5D71DFD762E1556AC535.jpg
//
//                StringBuilder sb1 = new StringBuilder();
//                sb1.append(PREFIX);
//                sb1.append(BOUNDARY);
//                sb1.append(LINEND);
//                sb1.append("Content-Disposition: form-data; name=\"" + fileInfoBean.getObjectKey() + "\"; filename=\""
//                        + fileName + "\"" + LINEND);
//                sb1.append("Content-Type: application/octet-stream; charset="
//                        + CHARSET + LINEND);
//                sb1.append(LINEND);
//                outStream.write(sb1.toString().getBytes());
//                outStream.write(fileInfoBean.getFileByte());
////                InputStream is = new FileInputStream(fileInfoBean.getFilePath());
////                byte[] buffer = new byte[1024];
////                int len = 0;
////                while ((len = is.read(buffer)) != -1) {
////                    outStream.write(buffer, 0, len);
////                }
////
////                is.close();
//                outStream.write(LINEND.getBytes());
//            }
//
//
//        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
//        outStream.write(end_data);
//        outStream.flush();
//
//        int res = conn.getResponseCode();
//        InputStream in = res==200?conn.getInputStream():conn.getErrorStream();
//        String data ;
//        ResponseInfoBean responseInfoBean = new ResponseInfoBean();
//        responseInfoBean.setCode(res);
//        int ch;
//        StringBuffer b = new StringBuffer();
//        InputStreamReader inread = new InputStreamReader(in,"utf-8");
//        while ((ch = inread.read()) != -1) {
//            b.append((char) ch);
//        }
//        data = b.toString().trim();
//        responseInfoBean.setMessage(data);
//
//        outStream.close();
//        conn.disconnect();
//        return responseInfoBean;
//    }
}
